<?php

session_start();

header('Access-Control-Allow-Origin:*');

date_default_timezone_set("PRC");

header("Content-Type: text/html;charset=utf8");

require_once '../common/in_mysql.php';
require_once '../db/version.db.php';

$action = filter_input(INPUT_POST, "action") ? filter_input(INPUT_POST, "action") : filter_input(INPUT_GET, "action");

$res = array();
switch ($action) {
    case 'listVersion':
        $res = listVersion();
        break;
    case 'addVersion':
        $res = addVersion();
        break;
    case 'editVersion':
        $res = editVersion();
        break;
    case 'deleteVersion':
        $res = deleteVersion();
        break;
    default :
}
echo json_encode($res);

function listVersion() {
    $res['code'] = 0;
    $res['msg'] = "";
    $versionDb = new VersionDb();
    $versionList = $versionDb->listVersion();

    for ($i = 0; $i < count($versionList); $i++) {
        $versionList[$i]['newCreate'] = $versionList[$i]['ctime'];
        unset($versionList[$i]['ctime']);
        unset($versionList[$i]['is_force']);
    }

    $res['data'] = $versionList;
    $res['count'] = count($versionList);
    return $res;
}

function addVersion() {
    $name = filter_input(INPUT_POST, "name");
    $ver = filter_input(INPUT_POST, "ver");
    $addr = filter_input(INPUT_POST, "addr");
    $scene = filter_input(INPUT_POST, "scene");

    if (trim($name) == "") {
        $res['code'] = 233;
        $res['msg'] = "请输入名称";
        return $res;
    }

    $versionDb = new VersionDb();

    $array = $versionDb->getVersionByName($name);
    if (count($array) > 0) {
        $res['code'] = 231;
        $res['msg'] = "name'" . $name . "'已经存在，请重新输入";
        return $res;
    }

    if ($versionDb->addVersion($name, $ver, $addr, $scene)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 230;
        $res['msg'] = "添加版本信息失败";
    }
    return $res;
}

function editVersion() {
    $id = filter_input(INPUT_POST, "id");
    $name = filter_input(INPUT_POST, "name");
    $ver = filter_input(INPUT_POST, "ver");


    if (trim($name) == "") {
        $res['code'] = 233;
        $res['msg'] = "请输入名称";
        return $res;
    }

    $versionDb = new VersionDb();

    $array = $versionDb->getVersionByName($name);
    if (count($array) > 0 && $array[0]['id'] != $id) {
        $res['code'] = 231;
        $res['msg'] = "name'" . $name . "'已经存在，请重新输入";
        return $res;
    }

    if ($versionDb->editVersion($id, $name, $ver)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 232;
        $res['msg'] = "编辑版本信息失败";
    }
    return $res;
}

function deleteVersion() {
    $id = filter_input(INPUT_POST, "id");
    $versionDb = new VersionDb();

    if ($versionDb->deleteVersion($id)) {
        $res['code'] = 0;
        $res['msg'] = "";
    } else {
        $res['code'] = 236;
        $res['msg'] = "删除版本信息失败";
    }
    return $res;
}
